package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.InitVodClient;
import com.atguigu.vod.utils.VodConstantUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author: 亚当
 * @date: 2022年06月30日 17:04
 * @package: com.atguigui.vod.controller
 * @Description: 阿里云视频服务
 */
@RestController
@CrossOrigin
@RequestMapping("/eduvod/video")
public class VodController {
    @Autowired
    private VodService vodService;

    //根据视频id删除阿里云视频
    @ApiOperation("根据视频id删除阿里云视频")
    @DeleteMapping("removeAliyunVideo/{id}")
    public R removeAliyunVideo(@PathVariable String id){
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(VodConstantUtils.KEY_ID, VodConstantUtils.KEY_SECRET);
            //创建视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(id);
            //调用初始化的方法实现删除
            client.getAcsResponse(request);
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除阿里云视频异常!!!");
        }
        return R.ok();
    }
    //上传视频到阿里云
    @ApiOperation("上传视频到阿里云")
    @PostMapping("uploadAliyunVideo")
    public R uploadAliyunVideo(MultipartFile file){
        String videoId = vodService.uploadVideoAliyun(file);
        return R.ok().data("videoId",videoId);
    }
    //删除多个阿里云视频的方法
    //参数多个视频id
    @ApiOperation("批量删除阿里云视频")
    @DeleteMapping("delete-batch")
    public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList){
        vodService.removeMoreAliyunVideo(videoIdList);
        return R.ok();
    }
    //根据视频id获取视频播放凭证
    @ApiOperation("根据视频id获取视频播放凭证")
    @GetMapping("getPalyAuth/{id}")
    public R getPalyAuth(@PathVariable String id){

        try {
            //创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(VodConstantUtils.KEY_ID, VodConstantUtils.KEY_SECRET);
            //创建获取凭证的request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request设置视频id
            request.setVideoId(id);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        }catch (Exception e){
            throw  new GuliException(20001,"获取视频凭证异常");
        }
    }
}
